package com.yicong.ants.ui.circle.article;

import android.graphics.drawable.Drawable;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.graphics.drawable.DrawableCompat;

import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.circle.ArticleItem;
import com.yicong.ants.databinding.ArticleEditActivityBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.UiAssistant;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.view.RichEditor;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author cch
 * @version 2020/8/22
 */
public class ArticleContentEditActivity extends BaseTitleBarActivity<ArticleEditActivityBinding> implements View.OnClickListener {
    RichEditor mEditor;
    TextView mPreview;
//    public static PopupWindow mLinkWindow;

    //region constant
    public static final int Tab_Gone = -1;
    public static final int Tab_a = 1;
    public static final int Tab_t = 2;

    public static final int A_color = 10;
    public static final int A_style = 11;
    public static final int T_align = 20;

    public static final int A_color_black = 1001;
    public static final int A_color_gray = 1004;
    public static final int A_color_green = 1005;
    public static final int A_color_pink = 1006;
    public static final int A_color_red = 1007;
    public static final int A_color_gold = 1008;

    public static final int A_style_bold = 1101;
    public static final int A_style_italic = 1102;
    public static final int A_style_delete = 1103;
    public static final int A_style_under = 1104;

    public static final int T_align_left = 2001;
    public static final int T_align_center = 2002;
    public static final int T_align_right = 2003;

    public static final int T_list_order = 2101;
    public static final int T_list_unorder = 2102;

    public static List<View> mColorMap = new ArrayList<>();
    public static List<View> mAlignMap = new ArrayList<>();
    public static List<View> mListMap = new ArrayList<>();
    public static List<View> mStyleMap = new ArrayList<>();
    public static List<View> mHeadMap = new ArrayList<>();
    //endregion

    List<LocalMedia> mMediaList = new ArrayList<>();
    boolean mIsEdit;
    ArticleItem mArticleItem;

    @Override
    protected int getLayout() {
        return R.layout.article_edit_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText("编辑文章内容");
        mDataBind.setClick(this);
        mMediaList = JsonHelper.toList(getIntent().getStringExtra(Constants.Extra.JSON), LocalMedia.class);
        if (getIntent().hasExtra(Constants.Extra.JSON2)) {
            mIsEdit = true;
            mArticleItem = JsonHelper.toObject(getIntent().getStringExtra(Constants.Extra.JSON2), ArticleItem.class);
            mDataBind.editor.setHtml(mArticleItem.getContent());
        }
        onLoadData();
        addTitleMenu();
        initMap();
        initViews();
    }

    private void addTitleMenu() {
        addTitleMenuItem(UiAssistant.getAtyMenuText(mContext, "发布"), view -> {
            if (StringHelper.isEmpty(mEditor.getHtml())) {
                showToast("请填写文章内容");
                return;
            }

            showProgress("正在发布");
            onUpload(0);
        });
    }

    void onUpload(int position) {
        if (position >= mMediaList.size() - 1) {
            onPublish();
            return;
        }
        LocalMedia media = mMediaList.get(position);
        if (StringHelper.isNotEmpty(media.getParentFolderName())
            && media.getParentFolderName().startsWith("http")) {
            onUpload(position + 1);
            return;
        }
        String path = AppHelper.getUploadPath(media);
        ImageHelper.uploadFile(mDisposable, path, uploadFileRespBean -> {
            //
            media.setParentFolderName(uploadFileRespBean.getData().getFile_url());
            onUpload(position + 1);
        }, throwable -> {
            hideProgress();
            Logs.logException(throwable);
            showToast("上传失败，请检查后再试");
        });
    }

    void onPublish() {
        Map<String, String> map = new HashMap<>();
        if (getIntent().hasExtra(Constants.Extra.Title)) {
            map.put("title", getIntent().getStringExtra(Constants.Extra.Title));
        }
        List<String> arr = new ArrayList<>();
        for (LocalMedia media : mMediaList) {
            if ("add".equals(media.getParentFolderName())) {
                continue;
            }
            arr.add(media.getParentFolderName());
        }
        map.put("cover", StringUtils.join(arr.toArray(), ","));
        map.put("content", mEditor.getHtml());
        showProgress();

        if (mIsEdit) {
            map.put("id", mArticleItem.getId());
        }
        addSubscribe(RetrofitHelper.getApis().publishArticle(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                showToast(respBean.getMsg());
                if (respBean.isCodeFail()) {
                    return;
                }
                RxBus.get().postEvent(Constants.Event.Circle_Aritcle_Suc);
                PrefHelper.remove(Constants.Prefs.Circle_Article_Draft);
                finish();
            }, RxHelper.getHideProgressConsumer(this)));
    }

    private void initMap() {
        mColorMap.add(mDataBind.editBlack);
        mColorMap.add(mDataBind.editGray);
        mColorMap.add(mDataBind.editGreen);
        mColorMap.add(mDataBind.editRed);
        mColorMap.add(mDataBind.editGold);

        mStyleMap.add(mDataBind.editBold);
        mStyleMap.add(mDataBind.editStrikeThrough);
        mStyleMap.add(mDataBind.editUnderLine);
        mStyleMap.add(mDataBind.editItalic);

        mAlignMap.add(mDataBind.alignCenter);
        mAlignMap.add(mDataBind.alignLeft);

        mListMap.add(mDataBind.editOrder);
        mListMap.add(mDataBind.editUnorder);

        mHeadMap.add(mDataBind.editH1);
        mHeadMap.add(mDataBind.editH3);
        mHeadMap.add(mDataBind.editH4);
    }

    private void initViews() {
        mEditor = mDataBind.editor;
        mEditor.setEditorHeight(200);
        mEditor.setEditorFontSize(22);
        mEditor.setEditorFontColor(UiHelper.getColor(R.color.text_222));
        //mEditor.setEditorBackgroundColor(Color.BLUE);
        //mEditor.setBackgroundColor(Color.BLUE);
        //mEditor.setBackgroundResource(R.drawable.bg);
        mEditor.setPadding(10, 10, 10, 10);
        //mEditor.setBackground("https://raw.githubusercontent.com/wasabeef/art/master/chip.jpg");
        mEditor.setPlaceholder("请输入广告展示内容");
        //mEditor.setInputEnabled(false);

        mPreview = mDataBind.preview;
        mEditor.setOnTextChangeListener(text -> {
            //
            mPreview.setText(text);
        });

        if (PrefHelper.contains(Constants.Prefs.Circle_Article_Draft) && !mIsEdit) {

            UiHelper.showCancelDialog(mContext, "检测到存在草稿，是否恢复编辑？",
                Pair.create("取消", (dialog, which) -> dialog.dismiss()),
                Pair.create("确定", (dialog, which) -> {
                    dialog.dismiss();
                    mEditor.setHtml(PrefHelper.getString(Constants.Prefs.Circle_Article_Draft));
                }));
        }

        mDataBind.editor.setOnDecorationChangeListener((text, types) -> {
            ArrayList<String> flagArr = new ArrayList<>();
            for (int i = 0; i < types.size(); i++) {
                flagArr.add(types.get(i).name());
            }

            if (flagArr.contains("BOLD")) {
                toggleCheck(mStyleMap, mDataBind.editBold);
            }
            decorationChange(flagArr, "BOLD", mDataBind.editBold);
            decorationChange(flagArr, "ITALIC", mDataBind.editItalic);
            decorationChange(flagArr, "UNDERLINE", mDataBind.editUnderLine);
            decorationChange(flagArr, "STRIKETHROUGH", mDataBind.editStrikeThrough);

            decorationChange(flagArr, "ORDEREDLIST", mDataBind.editOrder);
            decorationChange(flagArr, "UNORDEREDLIST", mDataBind.editUnorder);

            decorationChange(flagArr, "JUSTIFYLEFT", mDataBind.alignLeft);
            decorationChange(flagArr, "JUSTIFYCENTER", mDataBind.alignCenter);
//            decorationChange(flagArr, "JUSTIFYLEFT", mDataBind.alignRight);

            decorationChange(flagArr, "H4", mDataBind.editH4);
            decorationChange(flagArr, "H3", mDataBind.editH3);
            decorationChange(flagArr, "H1", mDataBind.editH1);
        });
    }

    public void decorationChange(ArrayList<String> arr, String flag, View checkView) {
        if (arr.contains(flag)) {
            tagView(checkView, true);
        } else {
            tagView(checkView, false);
        }
    }

    int checkColor = UiHelper.getColor(R.color.text_ddd);

    void checkEditView(View checkView) {
        tagView(checkView, true);
    }

    public void singleCheck(List<View> map, View checkView) {
        for (View view : map) {
            view.setBackgroundColor(0);
        }
        checkView.setBackgroundColor(checkColor);
    }

    public void toggleCheck(List<View> map, View checkView) {
        for (View view : map) {
            if (view != checkView) {
                continue;
            }

            if (checkView.getTag() == null || checkView.getTag() == "0") {
                tagView(checkView, true);
            } else {
                tagView(checkView, false);
            }
        }
    }

    /**
     * 单选开光，比如 标题 h1
     */
    public void singleToggleCheck(List<View> map, View checkView) {
        if ("1".equals(checkView.getTag())) {
            tagView(checkView, false);
            return;
        }
        for (View view : map) {
            if (view != checkView) {
                tagView(checkView, false);
                continue;
            }
            tagView(checkView, true);
        }
    }

    private void tagView(View checkView, boolean toggle) {
        checkView.setTag(toggle ? "1" : "0");
        checkView.setBackgroundColor(toggle ? checkColor : 0);
    }

    @Override
    protected void onLoadData() {
        if (!getIntent().hasExtra(Constants.Extra.Id)) {
            return;
        }
        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("id", getIntent().getStringExtra(Constants.Extra.Id));
        addSubscribe(RetrofitHelper.getApis().htmlContent(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    return;
                }
                mEditor.setHtml(StringEscapeUtils.unescapeHtml4(respBean.getData()));
            }, RxHelper.getHideProgressConsumer(this)));
    }

    void toggleView(View v) {
        if (!(v instanceof ImageView)) {
            return;
        }
        boolean toggle = v.getTag() == null || "0".equals(v.getTag());
        ImageView view = (ImageView) v;
        Drawable drawable = view.getDrawable();
        DrawableCompat.setTint(drawable, UiHelper.getColor(toggle ? R.color.orange : R.color.text_888));
        view.setImageDrawable(drawable);
        view.setTag(toggle ? "1" : "0");
    }

    @Override
    public void onBackPressed() {
        if (StringHelper.isEmpty(mEditor.getHtml())) {
            finish();
            return;
        }
        if (getIntent().hasExtra(Constants.Extra.Id)) {
            finish();
            return;
        }
        UiHelper.showCancelDialog(mContext, "是否保存草稿?",
            Pair.create("不保存", (dialog, which) -> {
                dialog.dismiss();
                finish();
            }),
            Pair.create("保存草稿", (dialog, which) -> {
                PrefHelper.putString(Constants.Prefs.Circle_Article_Draft, mEditor.getHtml());
                dialog.dismiss();
                finish();
            }));
    }

    void showField(int tabName) {
        switch (tabName) {
            case Tab_a:
                UiHelper.setVisibleElseGone(mDataBind.fieldA, !UiHelper.isVisible(mDataBind.fieldA));
                UiHelper.setVisibleElseGone(mDataBind.fieldT, false);
                break;
            case Tab_t:
                UiHelper.setVisibleElseGone(mDataBind.fieldT, !UiHelper.isVisible(mDataBind.fieldT));
                UiHelper.setVisibleElseGone(mDataBind.fieldA, false);
                break;
            case Tab_Gone:
                UiHelper.setVisibleElseGone(mDataBind.fieldT, false);
                UiHelper.setVisibleElseGone(mDataBind.fieldA, false);
                break;
        }
    }

    /*    private void showLinkWindow() {
        final PopupWindow popupWindow = new PopupWindow(textView,200,300);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher_background));//设置背景
        mTestButton = (Button)findViewById(R.id.test_btn);
        mTestButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.showAsDropDown(mTestButton);

            }
        });
    }*/

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBackPressed();
                break;

            //region tab
            case R.id.edit_tab_font:
                showField(Tab_a);
                break;
            case R.id.edit_tab_text:
                showField(Tab_t);
                break;
            case R.id.edit_tab_link:
                showField(Tab_Gone);
                Dialogs.showHtmlLinkEdit(mContext, str -> {
                    String[] arr = str.split("##");
                    mEditor.insertLink(arr[1], arr[0]);
                });
                break;
            case R.id.edit_tab_undo:
                mEditor.undo();
                break;
            //endregion

            //region color
            case R.id.edit_green:
                singleCheck(mColorMap, v);
                mEditor.setTextColor(UiHelper.getColor(R.color.green));
                break;
            case R.id.edit_red:
                singleCheck(mColorMap, v);
                mEditor.setTextColor(UiHelper.getColor(R.color.red));
                break;
            case R.id.edit_gold:
                singleCheck(mColorMap, v);
                mEditor.setTextColor(UiHelper.getColor(R.color.gold));
                break;
            case R.id.edit_black:
                singleCheck(mColorMap, v);
                mEditor.setTextColor(UiHelper.getColor(R.color.text_222));
                break;
            case R.id.edit_gray:
                singleCheck(mColorMap, v);
                mEditor.setTextColor(UiHelper.getColor(R.color.text_666));
                break;
            //endregion

            //region style
            case R.id.edit_italic:
                toggleCheck(mStyleMap, v);
                mEditor.setItalic();
                break;
            case R.id.edit_bold:
                toggleCheck(mStyleMap, v);
                mEditor.setBold();
                break;
            case R.id.edit_under_line:
                toggleCheck(mStyleMap, v);
                mEditor.setUnderline();
                break;
            case R.id.edit_strike_through:
                toggleCheck(mStyleMap, v);
                mEditor.setStrikeThrough();
                break;
            //endregion

            //region align
            case R.id.align_center:
                singleCheck(mAlignMap, v);
                mEditor.setAlignCenter();
                break;
            case R.id.align_left:
                singleCheck(mAlignMap, v);
                mEditor.setAlignLeft();
                break;
//            case R.id.align_right:
//                singleCheck(mAlignMap, v);
//                mEditor.setAlignRight();
//                break;
            //endregion

            //region head
            case R.id.edit_h1:
                singleToggleCheck(mHeadMap, v);
                mEditor.setHeading(1);
                break;
            case R.id.edit_h3:
                singleToggleCheck(mHeadMap, v);
                mEditor.setHeading(3);
                break;
            case R.id.edit_h4:
                singleToggleCheck(mHeadMap, v);
                mEditor.setHeading(4);
                break;
            //endregion

            case R.id.edit_order:
                singleToggleCheck(mListMap, v);
                mEditor.setNumbers();
                break;
            case R.id.edit_unorder:
                singleToggleCheck(mListMap, v);
                mEditor.setBullets();
                break;
            case R.id.edit_tab_image:
                showField(Tab_Gone);
                UiHelper.setVisibleElseGone(mDataBind.insertField
                    , mDataBind.insertField.getVisibility() == View.GONE);
                break;
            case R.id.image:
                UiHelper.setVisibleElseGone(mDataBind.insertField, false);
                addImage(SelectMimeType.ofImage());
                break;
            case R.id.video:
                UiHelper.setVisibleElseGone(mDataBind.insertField, false);
                addImage(SelectMimeType.ofVideo());
                break;
            case R.id.audio:
                UiHelper.setVisibleElseGone(mDataBind.insertField, false);
                addImage(SelectMimeType.ofAudio());
                break;
        }
    }

    private void addImage(int type) {
//        PictureSelector.create(this)
//            .openGallery(type)
//            .selectionMode(PictureConfig.SINGLE)
//            .isEnableCrop(true)
//            .freeStyleCropEnabled(true)
//            .isCompress(true)
//            .compressQuality(90)
//            .imageEngine(GlideEngine2.createGlideEngine())
//            .forResult(new OnResultCallbackListener<LocalMedia>() {
//                @Override
//                public void onResult(List<LocalMedia> result) {
//                    if (CollectionHelper.isEmpty(result)) {
//                        return;
//                    }
//
//                    String path = result.get(0).getRealPath();
//                    if (result.get(0).isCompressed()) {
//                        path = result.get(0).getCompressPath();
//                    }
//                    // 结果回调
//                    showProgress("正在上传");
//                    ImageHelper.uploadFile(mDisposable, path, respBean -> {
//                        hideProgress();
//                        if (respBean.isCodeFail()) {
//                            showError();
//                            return;
//                        }
//
//                        switch (type) {
//                            case PictureConfig.TYPE_IMAGE:
//                                mEditor.insertImage(respBean.getData().getFile_url(), "alt");
//                                break;
//                            case PictureConfig.TYPE_VIDEO:
//                                mEditor.insertVideo(respBean.getData().getFile_url());
//                                break;
//                            case PictureConfig.TYPE_AUDIO:
//                                mEditor.insertAudio(respBean.getData().getFile_url());
//                                break;
//                        }
//                    }, throwable -> {
//                        showError();
//                        Logs.logException(throwable);
//                    });
//                }
//
//                @Override
//                public void onCancel() {
//                    // 取消
//                }
//            });
    }
}
